﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
public class BakeVertexAnimation:EditorWindow {
	
	GameObject selectObj;
	VertexAnimationData  data;
	string path;
	bool canBake;
	bool canClose;

	[MenuItem("Assets/BakerAnimation")]
	public static void Init30(){
		EditorApplication.isPlaying = true;
		GetWindow<BakeVertexAnimation> ().InitData ();
	}
	void InitData(){
		selectObj = Selection.activeObject as GameObject;
		if (selectObj != null) {
			path = AssetDatabase.GetAssetPath (selectObj);
			name = Path.GetFileNameWithoutExtension (path);
			path = Path.GetDirectoryName (path) + "/" + name;
		}
		selectObj = GameObject.Instantiate (selectObj);
		canBake = true;
	}
	void OnGUI(){
//		if (GUILayout.Button ("Bake"))
//			Bake ();
		if (canBake && !EditorApplication.isPlayingOrWillChangePlaymode) {
			canBake = false;
			Bake ();
			canClose = true;

		}

	}
	void Update(){
		if (canClose) {
			canClose = false;
			EditorApplication.isPlaying = false;
			Close ();	
		}
	}
	public void Bake(){
		
		if (selectObj != null) {
			data = ScriptableObject.CreateInstance<VertexAnimationData>();//创建Test的一个实例
			BakeVertex ();
			GameObject.DestroyImmediate (selectObj);
		}
	}
	public static int FPS = 30;
	public void BakeVertex(){

		Animator ani = selectObj.GetComponentInChildren<Animator> (true);
		SkinnedMeshRenderer skin = selectObj.GetComponentInChildren<SkinnedMeshRenderer> (true);
		if (ani == null || skin == null)
			return;
		skin.transform.position = Vector3.zero;
		skin.transform.eulerAngles = Vector3.zero;
		for (int i = 0; i < ani.runtimeAnimatorController.animationClips.Length; i++) {
			data.Add(CreateClip (ani,ani.runtimeAnimatorController.animationClips [i], path,skin,FPS));
		}
		data.fps = FPS;
		data.material = skin.sharedMaterial;
		data.uv = skin.sharedMesh.uv;
		data.triangles = skin.sharedMesh.triangles;
		AssetDatabase.CreateAsset(data , path+"_clip.asset");
		AssetDatabase.Refresh();
	}
	public static VertexAnimationClip CreateClip(Animator ani,AnimationClip clip,string path,SkinnedMeshRenderer skin,float fps){
		

		VertexAnimationClip clipData = new VertexAnimationClip();

		List<MeshData> meshData = new List<MeshData>();
		Mesh mesh = new Mesh ();

		ani.Play (clip.name);
		float clipTime = clip.length;
		int count = (int)(clipTime * fps);
		for (int i = 0; i < count; i++) {
			ani.Update (1/fps);
			skin.BakeMesh (mesh);

			meshData.Add (new MeshData (mesh));
		}


		clipData.meshData = meshData;
		clipData.name = clip.name;
		clipData.clipTime = clipTime;
		return clipData;

	}

}

